package com.mmall.common.aop;

import com.mmall.common.enums.HttpMethodEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gg
 * @version LogRecordAspect.java, v 0.1 2019-05-27 9:56 gg
 */
@Slf4j
@Aspect
@Configuration
public class LogRecordAspect {

    @Pointcut("execution(* com.mmall.*.controller..*.*(..))")
    public void excludeService() {
    }

    @Around("excludeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        LocalDateTime startTime = LocalDateTime.now();
        if (sra != null) {
            HttpServletRequest request = sra.getRequest();
            String url = request.getRequestURL().toString();
            String method = request.getMethod();
            Object[] args = pjp.getArgs();

            log.info("===============++++请求开始++++================");
            log.info("地址:" + url);
            log.info("类型:" + method);
            log.info("参数:");
            //获取请求参数集合并进行遍历拼接
            if (args.length > 0) {
                if (HttpMethodEnum.POST.getName().equals(method)) {
                    Object object = args[0];
                    Map<String, Object> paramMap = getKeyAndValue(object);
                    for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                        log.info("{} : {}", entry.getKey(), entry.getValue());
                    }
                } else if (HttpMethodEnum.GET.getName().equals(method)) {
                    Map<String, String[]> map = request.getParameterMap();
                    for (Map.Entry<String, String[]> entry : map.entrySet()) {
                        log.info("{} : {}", entry.getKey(), Arrays.toString(entry.getValue()));
                    }
                }
            }
        }
        Object proceed = pjp.proceed();
        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime, endTime);
        log.info("===============++++请求结束 耗时：" + duration.getSeconds() + " 秒 ++++================");
        return proceed;
    }

    public static Map<String, Object> getKeyAndValue(Object obj) {
        Map<String, Object> map = new HashMap<>(16);
        // 得到类对象
        Class userCla = obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = userCla.getDeclaredFields();
        for (Field f : fs) {
            // 设置些属性是可以访问的
            f.setAccessible(true);
            Object val;
            try {
                // 得到此属性的值
                val = f.get(obj);
                // 设置键值
                map.put(f.getName(), val);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}